<?php

class HTech_Controller_Plugin_Initialize extends Zend_Controller_Plugin_Abstract
{
    protected $_config;

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName();
        $controller = $request->getControllerName();
        $action = $request->getActionName();
        $resource = sprintf('%s.%s.%s', $module, $controller, $action);
        $identity = Zend_Auth::getInstance()->getIdentity();
        
        /*
         * Terminate script without notice if a wrong cl param is passed
         */
        if($request->getParam('cl')) {
            $clo = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini', 'cl');
            $cla = $clo->toArray();
            if(!isset($cla[$request->getParam('cl')])) exit;
        }
        
        if($identity) {
            /*
             * Extending session expiration time
             * Beware that php.ini settings
             * take precedence so adjust php.ini accordingly
             * 
             */
             //$session = $this->_getAuthSession();
             //$session->setExpirationSeconds(60*60*24);
            
            /*
             * Re-route to auth.index.deny non-valid requests 
             * from authenticated users
             */
            if(!isset($identity->resources[$resource])) {
                $request->setModuleName('default')->setControllerName('auth')->setActionName('deny');
            }
            
            //if(Zend_Auth::getInstance()->hasIdentity()) {} 
            /*
             * Valid resource request from authenticated user
             */
            $this->_initConfig();

            date_default_timezone_set($this->_config->timezone);
            Zend_Date::setOptions(array('format_type' => 'php'));

            $this->_initLocale($request->getParam('locale'));
            $this->_initTranslate();
            $this->_initLayout($request->getModuleName());
            $this->_initDB();
            $this->_initCurrencyHelper();
            
        } elseif($request->getParam('cl')) {
            /*
             * Valid cl login requests from non authenticated users
             */
            Zend_Registry::set('clName', $cla[$request->getParam('cl')]['name']);
            Zend_Registry::set('cl', $request->getParam('cl'));
            Zend_Registry::set('Zend_Locale', $request->getParam('locale'));
            HTech_Locale::setLocaleObj($request->getParam('locale'));
            HTech_Locale::setTranslateObj();
            
        } else {
            /*
             * Requests from non authenticated users, who are not asking
             * for the login page (cl).
             * Chances are:
             * 1. Open resource request
             * 2. Request from an expired session
             * 3. Non-existent resource request
             * Options 2 and 3 are re-routed to a session expired page
             */
            $conf = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini');
            if(!isset($conf->open_resources->$module->$controller->$action)) {
                $request->setModuleName('default')->setControllerName('auth')->setActionName('expired'); 
            }
        } 
        
        set_include_path(get_include_path() . PATH_SEPARATOR . 
                APPLICATION_PATH . DIRECTORY_SEPARATOR . 'modules' . 
                DIRECTORY_SEPARATOR . $request->getModuleName() . 
                DIRECTORY_SEPARATOR . 'models'); 
                
    }
    
    /**
     * Load config options
     * If not possible the execution stops here without notice
     * rendering a blank/empty page
     *
     * @return void
     */
    protected function _initConfig()
    {
        try {
            $cl = Zend_Auth::getInstance()->getIdentity()->emmsClient;
            $db = Zend_Auth::getInstance()->getIdentity()->emmsDb;
            $this->_config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini', $cl . '_' . $db);
            Zend_Registry::set('emmsClient', $cl);
            Zend_Registry::set('emmsDb', $db);
            Zend_Registry::set('HT_Config', $this->_config);
        } catch(Exception $e) {
            /*
             * @todo
             * log exception message
             */
            $e->getMessage();
            Zend_Auth::getInstance()->clearIdentity();
            exit;
        }
    }

    /**
     * Setup locale
     *
     * @param  string $locale
     * @return void
     */
    protected function _initLocale($locale = '')
    {
        if(Zend_Locale::isLocale($locale)) {
            Zend_Registry::set('Zend_Locale', new Zend_Locale($locale));
            $data = Zend_Auth::getInstance()->getStorage()->read();
            $data->locale = Zend_Registry::get('Zend_Locale');
            Zend_Auth::getInstance()->getStorage()->write($data);
        } else {
            $locale = Zend_Auth::getInstance()->getIdentity()->locale;
            Zend_Registry::set('Zend_Locale', $locale);
        }
    }

    /**
     * Setup translate
     *
     * @return void
     */
    protected function _initTranslate()
    {
        $locale = Zend_Registry::get('Zend_Locale'); 
        $translate = new Zend_Translate(
        array
        (
            'adapter' => 'gettext',
            'content' => APPLICATION_PATH . '/../languages/'
                                          . $locale->getLanguage()
                                          . '.mo',
            'locale'  => $locale
        ));
        Zend_Registry::set('Zend_Translate', $translate);
    }

    /**
     * Setup layout
     *
     * @param  string $module
     * @return void
     */
    protected function _initLayout($module = 'default')
    { 
        $layout = Zend_Controller_Front::getInstance()
                      ->getParam('bootstrap')->getOption('layout');
        if(!isset ($layout[$module])) {
            $layout[$module] = $layout['default'];
        }
        Zend_Layout::getMvcInstance()->setLayout($layout[$module]);
    }

    /**
     * Setup db
     *
     * @return void
     */
    protected function _initDB()
    {
        $dbOptions = Zend_Controller_Front::getInstance()
                        ->getParam('bootstrap')->getOption('db');
        $db = Zend_Db::factory($dbOptions['adapter'], $this->_config->db->toArray());
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        Zend_Registry::set('db', $db);
        Zend_Db_Table_Abstract::setDefaultAdapter($db);
    }
    
    protected function _initCurrencyHelper()
    {
        $currency = new Zend_Currency($this->_config->locale->default);
        Zend_Registry::set('Zend_Currency', $currency);
    }

}
